dict
assignment¶meals = {}
meals
meals['breakfast'] = 'cereal'
meals
meals['lunch'] = 'sandwich'
meals
meals['second breakfast'] = "I don't think he knows about second breakfast!"
meals
count_letters.py
¶NOTES
counts = {}
if letter not in counts
: if we haven't seen that letter before, what do we do?if
block necessary? What will happen on counts[letter] += 1
if we don't have it?counts[letter] += 1
: what does this mean? What does it do? Lookup value, add 1, reassign to key.%%file count_letters.py
def count_letters(text):
counts = {}
for letter in text:
if letter not in counts:
counts[letter] = 0
counts[letter] += 1
return counts
print(count_letters('banana abacus cabana'))
! python count_letters.py
Common pattern:
0 always comes before 1, which always comes before 2.
Given a passage of words, count the occurrence of each word. Strip punctuation and ignore casing.
count_words.py
¶def count_words(text):
counts = {}
for word in text.split():
word = word.strip('.,!?;').lower()
if word not in counts:
counts[word] = 0
counts[word] += 1
return counts
print(count_words("Row, row, row, your boat... and hope your boat floats!"))
group_by_first_letter.py
¶NOTES
groups[key] = []
: here we initialize a group with an empty listgroups[key].append(word)
: here we append the word to the list in groups[key]
key = word[0]
: here we decide what the things in a group have in commonGroup a sequence of words by their length.
group_by_size.py
¶def group_by_size(words):
groups = {}
for word in words:
key = len(word)
if key not in groups:
groups[key] = []
groups[key].append(word)
return groups
states = 'Utah Idaho Oregon California Washington Arizona Iowa Ohio Mississippi Florida Kansas Maine'.split()
print(group_by_size(states))